package wymiana.mbeans.school;

import java.io.ByteArrayInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

import wymiana.domain.Photo;
import wymiana.domain.School;
import wymiana.service.PhotoService;
import wymiana.service.SchoolService;

@ManagedBean(name = "schoolMBean")
// @RequestScoped
@SessionScoped
public class SchoolMBean implements Serializable {

	/** serialization uid */
	private static final long serialVersionUID = 4639453603000276510L;

	/** lista szkol */
	private List<School> schools = null;
	/** lista szkol */
	private List<School> filteredSchools = null;

	/** aktualnie wybrana uczelnia */
	private School actualSchool = null;

	@ManagedProperty("#{schoolService}")
	private SchoolService schoolService;

	@ManagedProperty("#{photoService}")
	private PhotoService photoService;

	private Map<String, UploadedFile> uploadedFiles;

	private List<String> listImages;

	public SchoolMBean() {
		// TODO inicjalizacja MBeana

	}

	public String goToSchools() {
		return "school";
	}

	public String editSchool() {
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();

		String schoolId = (String) externalContext.getRequestParameterMap()
				.get("schoolId");

		this.listImages = new ArrayList<String>();
		this.uploadedFiles = new HashMap<String, UploadedFile>();
		actualSchool = schoolService.getSchool(Integer.parseInt(schoolId));
		return "editSchool";
	}

	public String addSchool() {
		actualSchool = new School();
		this.listImages = new ArrayList<String>();
		this.uploadedFiles = new HashMap<String, UploadedFile>();
		return "addSchool";
	}

	public String removeSchool() {
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();

		String schoolId = (String) externalContext.getRequestParameterMap()
				.get("schoolId");
		// School s = schoolService.getSchool(Integer.parseInt(schoolId));
		setSchools(null);

		schoolService.deleteSchoolByID(Integer.parseInt(schoolId));
		return "";
	}

	public String showSchool() {
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();

		String schoolId = (String) externalContext.getRequestParameterMap()
				.get("schoolId");

		actualSchool = schoolService.getSchool(Integer.parseInt(schoolId));

		return "showSchool";
	}

	public void upload(FileUploadEvent event) {
		FacesMessage msg = new FacesMessage("Sukces! ", event.getFile()
				.getFileName() + " zostało dodane.");

		FacesContext.getCurrentInstance().addMessage(null, msg);
		UploadedFile file = event.getFile();
		String key = file.getFileName();
		if (this.uploadedFiles == null) {
			this.uploadedFiles = new HashMap<String, UploadedFile>();
		}
		this.uploadedFiles.put(key, file);
		if (this.listImages == null) {
			this.listImages = new ArrayList<String>();
		}
		this.listImages.add(key.toString());
	}

	public String deletePhoto() {
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();

		String imageId = (String) externalContext.getRequestParameterMap().get(
				"imageId");
		uploadedFiles.remove(imageId);
		listImages.remove(imageId);

		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Sukces: ", "Usunięto obraz z listy");

		FacesContext.getCurrentInstance().addMessage(null, message);

		return "";

	}

	public String saveSchool() {

		if (actualSchool.getIdSchool() == null) {
			actualSchool.setCreationDate(new Date());
			schoolService.create(actualSchool);
		}
		List<Photo> photos = new ArrayList<Photo>();
		if (this.listImages != null) {
			for (String key : this.listImages) {
				Photo p = new Photo();
				UploadedFile f = (UploadedFile) this.uploadedFiles.get(key);
				p.setMainPhoto(Boolean.valueOf(true));
				p.setPhoto(f.getContents());
				photos.add(p);
				p.setSchool(this.actualSchool);
			}
		}
		if (!photos.isEmpty()) {
			this.photoService.addPhotos(photos);
			if (actualSchool.getPhotos() == null) {
				actualSchool.setPhotos(photos);
			} else {
				this.actualSchool.getPhotos().addAll(photos);
			}
		}

		this.schoolService.updateSchool(actualSchool);

		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Sukces: ", "Zapisano zmiany");

		FacesContext.getCurrentInstance().addMessage(null, message);
		boolean contains = false;

		for (School s : getSchools()) {
			if (s.getIdSchool().equals(actualSchool.getIdSchool())) {
				contains = true;
				getSchools().remove(s);
				getSchools().add(actualSchool);
			}
		}

		if (!contains) {
			getSchools().add(actualSchool);
			actualSchool = null;
		}

		listImages = null;
		uploadedFiles = null;

		return "school";
	}

	public String saveEditedSchool() {
		saveSchool();
		return "";
	}

	public StreamedContent getImage() {
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();

		if (FacesContext.getCurrentInstance().getRenderResponse()) {
			// So, we're rendering the view. Return a stub StreamedContent so
			// that it will generate right URL.
			return new DefaultStreamedContent();
		} else {
			String imageId = (String) externalContext.getRequestParameterMap()
					.get("imageIdD");
			Photo p = null;
			if (actualSchool.getPhotos() != null) {
				for (Photo photo : actualSchool.getPhotos()) {
					if (photo.getIdPhoto().toString().equals(imageId)) {
						p = photo;
					}
				}
			}
			StreamedContent image = null;
			if (p != null) {
				image = new DefaultStreamedContent(new ByteArrayInputStream(
						p.getPhoto()), "image/png");

				return image;
			}
		}

		return null;
	}

	public String deleteActualPhoto() {
		ExternalContext externalContext = FacesContext.getCurrentInstance()
				.getExternalContext();

		String imageId = (String) externalContext.getRequestParameterMap().get(
				"imageIdD");

		photoService.deleteById(Integer.parseInt(imageId));
		int i = 0;
		for (Photo p : actualSchool.getPhotos()) {
			if (p.getIdPhoto().toString().equals(imageId)) {
				break;
			}
			i++;
		}
		actualSchool.getPhotos().remove(i);
		FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
				"Sukces: ", "Usunięto obraz");

		FacesContext.getCurrentInstance().addMessage(null, message);

		return "";
	}

	/**
	 * @return the schools
	 */
	public List<School> getSchools() {
		if (schools == null) {
			schools = schoolService.getAllSchools();
		}
		return schools;
	}

	/**
	 * @return the schoolService
	 */
	public SchoolService getSchoolService() {
		return schoolService;
	}

	/**
	 * @param schools
	 *            the schools to set
	 */
	public void setSchools(List<School> schools) {
		this.schools = schools;
	}

	/**
	 * @param schoolService
	 *            the schoolService to set
	 */
	public void setSchoolService(SchoolService schoolService) {
		this.schoolService = schoolService;
	}

	/**
	 * @return the actualSchool
	 */
	public School getActualSchool() {
		return actualSchool;
	}

	/**
	 * @param actualSchool
	 *            the actualSchool to set
	 */
	public void setActualSchool(School actualSchool) {
		this.actualSchool = actualSchool;
	}

	/**
	 * @return the uploadedFiles
	 */
	public Map<String, UploadedFile> getUploadedFiles() {
		return uploadedFiles;
	}

	/**
	 * @param uploadedFiles
	 *            the uploadedFiles to set
	 */
	public void setUploadedFiles(Map<String, UploadedFile> uploadedFiles) {
		this.uploadedFiles = uploadedFiles;
	}

	/**
	 * @return the listImages
	 */
	public List<String> getListImages() {
		return listImages;
	}

	/**
	 * @param listImages
	 *            the listImages to set
	 */
	public void setListImages(List<String> listImages) {
		this.listImages = listImages;
	}

	/**
	 * @return the photoService
	 */
	public PhotoService getPhotoService() {
		return photoService;
	}

	/**
	 * @param photoService
	 *            the photoService to set
	 */
	public void setPhotoService(PhotoService photoService) {
		this.photoService = photoService;
	}

	/**
	 * @return the filteredSchools
	 */
	public List<School> getFilteredSchools() {
		return filteredSchools;
	}

	/**
	 * @param filteredSchools
	 *            the filteredSchools to set
	 */
	public void setFilteredSchools(List<School> filteredSchools) {
		this.filteredSchools = filteredSchools;
	}

}
